/**
 * 临时数据模型
 *
 */
const mongoose = require('mongoose');
const EphemeralData = require('./mongo/ephemeral-data');
const PhoenixError = require('./phoenix-error');

function standardizeEphemeralData(data) {
  const standardData = {};
  standardData.key = data ? data._id : null;
  standardData.data = data ? JSON.parse(data.data) : null;
  return standardData;
}

async function createEphemeralData(data) {
  // 存储临时数据
  if (!data) {
    throw new PhoenixError('invalid request', 'need data');
  }
  const stringifyData = JSON.stringify(data);
  const created = await EphemeralData.create({
    data: stringifyData, createdDate: new Date(),
  });
  return standardizeEphemeralData(created.toObject());
}

async function getEphemeralData(id) {
  if (!id) {
    throw new PhoenixError('invalid request', 'need id');
  }
  const dataId = mongoose.Types.ObjectId(id);
  const data = await EphemeralData.findById(dataId).lean();
  return standardizeEphemeralData(data);
}

module.exports = {
  createEphemeralData,
  getEphemeralData,
};
